const Koa = require('koa');
const Router = require('koa-router');
const configset = require('./app/config/config');
const db = require('./app/config/database');
const betterBody = require('koa-better-body');
const convert = require('koa-convert');
// const babel = require('babel-polyfill');
// const static = require('koa-static');
const cors = require('koa2-cors');
const Json = require('koa-json');
const response = require('./app/libs/result');
const proving = require('./app/token/proving');
const moment = require('moment');
const common = require('./app/libs/common');
// const path = require('path');
// const common = require('./app/libs/common');
//const locale = require('koa-locale') //  detect the locale
//const render = require('koa-swig')   //  swig render
//const i18n = require('koa-i18n')

let server = new Koa()

//国际化
// Required!
// locale(server)
// server.use(i18n(server, {
//   directory: './config/locales',
//   locales: ['zh-CN', 'en'], //  `zh-CN` defualtLocale, must match the locales to the filenames
//   modes: [
//     'query',                //  optional detect querystring - `/?locale=en-US`
//     'subdomain',            //  optional detect subdomain   - `zh-CN.koajs.com`
//     'cookie',               //  optional detect cookie      - `Cookie: locale=zh-TW`
//     'header',               //  optional detect header      - `Accept-Language: zh-CN,zh;q=0.5`
//     'url',                  //  optional detect url         - `/en`
//     'tld',                  //  optional detect tld(the last domain) - `koajs.cn`
//     function() {}           //  optional custom function (will be bound to the koa context)
//   ]
// }))


let config={};
const env = process.env.NODE_ENV;
if (env === 'production') {
    config = configset.protConfig;
    console.log('当前生产环境：');
}else{
    config = configset.devConfig;
    console.log('当前开发环境：');
}
server.listen(config.port)
console.log(`服务已启动，监听${config.host}:${config.port}端口`);

server.use(convert(betterBody({
    fields: "body",
    formLimit: "50mb",//限制提交文件的最大值
    jsonLimit: "50mb",
    textLimit: "50mb"
})));
// server.use(body({
    
// }));
/**
 * 中间件 koa-better-body
 * 相关博客地址  
 * https://blog.csdn.net/shi851051279/article/details/99618239
 *  */ 
// server.use(body({
//     uploadDir: path.resolve(__dirname, './static/upload')
// }))

/**
 * koa-static 静态文件托管，上传的图片可以通过路径访问
 * 相关博客地址
 * https://blog.csdn.net/shi851051279/article/details/99618426
 *  */
// 如下两种写法都可以
// server.use(static(path.resolve(__dirname, './static/')))
//server.use(static(__dirname + '/static/'))

/**
 * koa2-cors解决跨域
 * 相关博客地址
 * https://blog.csdn.net/shi851051279/article/details/99617908
 *  */
server.use(cors({
    origin: '*',
    // function (ctx) {
    //     return '*'
    // },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS', 'PUT'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))
// server.use(cors({ credentials: true, exposeHeaders: ['token', 'Content-Disposition'] }));
server.use(Json());
/* 数据库连接并且挂载到context 对象上  */ 
server.context.db = db;
server.context.config = config;

let router = new Router();
// 统一处理token
router.use(async (ctx, next) => {

    try {
        // 记录请求日志
      let datenow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
      await ctx.db.query(`INSERT INTO post_log (created_time,updated_time,url,method,postobj,res,message,reqheader,reqhost) 
      VALUES(?,?,?,?,?,?,?,?,?)`, [datenow, datenow, ctx.request.url, ctx.request.method, JSON.stringify(ctx.request.body), "no response" , "",JSON.stringify(ctx.request.header),common.getClientIP(ctx.request)]);
      
   } catch (error) {
       console.log('请求日志写入出错'+error);
   }

    // 登录注册直接通过
    if (ctx.request.url.includes('about/contentwebsite') 
    || ctx.request.url.includes('product/loanstep')//借款步骤
    || ctx.request.url.includes('product/queryComment') //评论
    || ctx.request.url.includes('product/queryById')//产品详情
    || ctx.request.url.includes('product/querylist')//产品列表
    || ctx.request.url.includes('user/sendvcode')//发送验证码
    ||ctx.request.url.includes('consultation/querylist') //新闻列表
    ||ctx.request.url.includes('user/loginorregist')//登录
    ||ctx.request.url.includes('user/getperiod')
    ||ctx.request.url.includes('order/buildorder')
    ) {
        await next()
    } else {
        //await next()
        // 其他接口检测有没有携带token
        let token = ctx.request.header.authorization
        //token='token';
        //if (token && token.split(' ')[1]) {
            if (token) {
            let res = proving(token)
            //res=true;
            if (!res){
                // token 过期&& res.exp <= (new Date() / 1000)
                //response(ctx, 201, '', "登录过期")
                response(ctx, 201, '', "请登录")
                
            } else {
                await next()
            }
        } else {
            // 没有token
            response(ctx, 201, '', "请登录")
        }
    }
})

// 路由入口
// 测试接口
router.use('/api/v1/test', require('./app/api/test'));
//字典
router.use('/api/v1/dict', require('./app/api/dict'));

//通知
router.use('/api/v1/notice', require('./app/api/notice'));
//关于
router.use('/api/v1/about', require('./app/api/about'));
// 用户
router.use('/api/v1/user', require('./app/api/user'));
//订单
router.use('/api/v1/order', require('./app/api/order'));
// 产品
router.use('/api/v1/product', require('./app/api/product'));
// 广告
router.use('/api/v1/featured', require('./app/api/featured'));
// 资讯
router.use('/api/v1/consultation', require('./app/api/consultation'));

server.use(router.routes());


